package goodbaby.dklt.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.classic.core.fragment.BaseFragment;
import com.classic.core.utils.StringUtil;
import com.classic.core.utils.ToastUtil;
import com.classic.okhttp.gbb.http.ActionHelp;
import com.classic.okhttp.gbb.http.ObjectCallback;
import com.google.gson.reflect.TypeToken;
import com.tgd.gbb.uikit.ui.dialog.CommonDialog;
import com.tgd.gbb.uikit.ui.dialog.WLQQGagTimePicker;
import com.tgd.gbb.uikit.ui.refresh.PullToRefreshScrollView;
import com.tgd.gbb.uikit.ui.refresh.PullToRefreshUtil;
import com.tgd.gbb.uikit.ui.refresh.base.PullToRefreshBase;
import com.tgd.gbb.uikit.ui.widget.EditButtonView;
import com.tgd.gbb.uikit.ui.widget.MyListView;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import goodbaby.dklt.GbbApplication;
import goodbaby.dklt.GbbPreferences;
import goodbaby.dklt.R;
import goodbaby.dklt.activity.LoginActivity;
import goodbaby.dklt.activity.MainActivity;
import goodbaby.dklt.activity.MessageActivity;
import goodbaby.dklt.activity.UserActivity;
import goodbaby.dklt.adapter.ParentsCircleAdapter;
import goodbaby.dklt.bean.AttendanceClassBean;
import goodbaby.dklt.bean.AttendanceSchoolBean;
import goodbaby.dklt.bean.CardBean;
import goodbaby.dklt.bean.MessageInfo;
import goodbaby.dklt.bean.ParentsCricleBean;
import goodbaby.dklt.bean.PraiseBean;
import goodbaby.dklt.bean.ReviewBean;
import goodbaby.dklt.bean.SportInfo;

/**
 * Created by Jayden on 2016/4/19 14:01.
 *
 * @version V1.0
 * @Title: HomeFragment
 * @Description: 动态页
 */
public class HomeFragment extends BaseFragment implements EditButtonView.OnButtonClickListener {

    public static int toBigImage = 0;
    private Button btnCard;
    private CardBean card = new CardBean();
    private MainActivity context;
    private CommonDialog delDialog;
    private CommonDialog gagDialog;
    private EditButtonView editButtonView;
    private EditText editText;
    private int getDataType = 0;
    private InputMethodManager inputMethMgr;
    private boolean isHasMore = true;
    private ImageView ivMsg;
    private RelativeLayout rlMsg;
    private TextView tvUnreadMsg;
    private ImageView ivUser;
    private MyListView lvPc;
    private int mId;
    private int mPosition;
    private int mUserId;
    private String nickname = ":";
    private int pageNum = 1;
    private List<ParentsCricleBean> parentsCricleBeans = new ArrayList();
    private ParentsCircleAdapter pcAdapter;
    private PullToRefreshScrollView psView;
    private TextView tvDistance;
    private TextView tvHot;
    private TextView tvSleep;
    private TextView tvTitle;
    private TextView tvWalk;
    private TextView tvAttendanceType, tvAttendanceDetail;
    private int role;

    private PopupWindow popupWindow;


    private void delParentCircleMsg(int paramInt) {
        ActionHelp.gbbDelMsg(getActivity(), paramInt, new ObjectCallback<String>() {

            public void onError(int code) {
                if (code == 301) {
                    Intent intent = new Intent(getActivity(), LoginActivity.class);
                    startActivity(intent);
                } else {
                    ToastUtil.showToast(getActivity(), "删除失败!");
                }
            }

            public void onError(int paramAnonymousInt, String paramAnonymousString) {
                super.onError(paramAnonymousInt, paramAnonymousString);
            }

            public void onSuccess(String paramAnonymousString) {
                ToastUtil.showToast(getActivity(), "删除成功!");
                parentsCricleBeans.remove(mPosition);
                pcAdapter.notifyDataSetChanged();
//                initData();
            }

            @Override
            public Type getType() {
                return new TypeToken<String>() {
                }.getType();
            }
        });
    }

    private void hideSoftInput(View paramView) {
        inputMethMgr.hideSoftInputFromWindow(paramView.getWindowToken(), 0);
        editButtonView.setVisibility(View.GONE);
        editText.clearFocus();
        editText.setText("");
        MainActivity.llTabMain.setVisibility(View.VISIBLE);
        MainActivity.leftCenterButton.setVisibility(View.VISIBLE);
    }

    private void initAttendance() {
        if (role == 2) {
            ActionHelp.gbbAttendanceClass(getActivity(), "", new ObjectCallback<AttendanceSchoolBean>() {
                @Override
                public void onError(int code) {
                    if (code == 301) {
                        Intent intent = new Intent(getActivity(), LoginActivity.class);
                        startActivity(intent);
                    } else {
                        ToastUtil.showToast(activity, "失败:" + code);
                    }
                }

                @Override
                public void onSuccess(AttendanceSchoolBean response) {
                    tvAttendanceDetail.setText("全园总共" + response.getChildrenCount() + "人,请假" + response.getLevelCount() + "人,实到" + response.getAttendanceCount() + "人");
                    GbbApplication.setAttendanceSchoolBean(response);
                }

                @Override
                public Type getType() {
                    return new TypeToken<AttendanceSchoolBean>() {
                    }.getType();
                }
            });
        } else {
            String classId = StringUtil.getNumber(GbbPreferences.getClassId());
            ActionHelp.gbbAttendanceClass(getActivity(), classId, new ObjectCallback<AttendanceClassBean>() {
                @Override
                public void onError(int code) {
                    if (code == 301) {
                        Intent intent = new Intent(getActivity(), LoginActivity.class);
                        startActivity(intent);
                    } else {
                        ToastUtil.showToast(activity, "失败:" + code);
                    }
                }

                @Override
                public void onSuccess(AttendanceClassBean response) {
                    tvAttendanceDetail.setText("全班总共" + response.getChildrenCount() + "人,请假" + response.getLevelCount() + "人,实到" + response.getAttendanceCount() + "人");
                    GbbApplication.setAttendanceClassBean(response);
                }

                @Override
                public Type getType() {
                    return new TypeToken<AttendanceClassBean>() {
                    }.getType();
                }
            });
        }
    }

    private void initSportsInfo() {
        ActionHelp.getSportInfo(getActivity(), new ObjectCallback<SportInfo>() {

            public void onError(int code) {
                if (code == 301) {
                    Intent intent = new Intent(getActivity(), LoginActivity.class);
                    startActivity(intent);
                } else {
                    ToastUtil.showToast(HomeFragment.this.getActivity(), "请求错误");
                    tvWalk.setText("--");
                    tvHot.setText("--Cal");
                    tvDistance.setText("--M");
                    tvSleep.setText("--%");
                }
            }

            public void onSuccess(SportInfo paramAnonymousSportInfo) {
                tvWalk.setText(paramAnonymousSportInfo.getSportStep() + "");
                tvHot.setText(paramAnonymousSportInfo.getTakeEnergy() + "Cal");
                tvDistance.setText(paramAnonymousSportInfo.getSRange() + "M");
                tvSleep.setText(paramAnonymousSportInfo.getFinishValue() + "%");
            }

            @Override
            public Type getType() {
                return new TypeToken<SportInfo>() {
                }.getType();
            }
        });
    }

    private void loadMore() {
        if (isHasMore) {
            getDataType = 2;
            pageNum++;
            initData();
            PullToRefreshUtil.initLabel(getActivity(), psView);
        } else {
            PullToRefreshUtil.setLoadLabel(psView, "没有更多了");
            psView.onRefreshComplete();
        }
    }

    private void refrush() {
        getDataType = 1;
        pageNum = 1;
        PullToRefreshUtil.initLabel(getActivity(), psView);
        initData();
    }

    private void showInputSoft(int paramInt) {
        mPosition = paramInt;
        editButtonView.setVisibility(View.VISIBLE);
        editText.requestFocus();
        inputMethMgr.showSoftInput(editText, InputMethodManager.SHOW_FORCED);
        MainActivity.llTabMain.setVisibility(View.VISIBLE);
        MainActivity.leftCenterButton.setVisibility(View.VISIBLE);
    }

    private void submitComment(int paramInt1, String paramString, final int paramInt2) {
        ActionHelp.gbbPubComment(getActivity(), paramInt1, paramInt2, paramString, new ObjectCallback<String>() {

            public void onError(int paramAnonymousInt) {
                if (paramInt2 == 0)
                    ToastUtil.showToast(HomeFragment.this.getActivity(), "评论失败");
            }

            public void onSuccess(String paramAnonymousString) {
                if (paramInt2 == 0)
                    ToastUtil.showToast(HomeFragment.this.getActivity(), "评论成功");
            }

            @Override
            public Type getType() {
                return new TypeToken<String>() {
                }.getType();
            }
        });
    }

    public void closeBottom() {
        editButtonView.setVisibility(View.VISIBLE);
        editText.requestFocus();
        MainActivity.llTabMain.setVisibility(View.GONE);
        MainActivity.leftCenterButton.setVisibility(View.GONE);
    }

    public int getLayoutResId() {
        return R.layout.fragment_home;
    }

    public boolean getUserVisibleHint() {
        return super.getUserVisibleHint();
    }

    public void initData() {
        super.initData();
        nickname = GbbPreferences.getName();
        role = Integer.parseInt(GbbPreferences.getRole());
        ActionHelp.gbbMessages(getActivity(), this.pageNum, new ObjectCallback<List<ParentsCricleBean>>() {

                    public void onError(int code) {
                        if (getDataType != 0)
                            psView.onRefreshComplete();
                        if (code == 301) {
                            Intent intent = new Intent(getActivity(), LoginActivity.class);
                            startActivity(intent);
                        } else {
                            ToastUtil.showToast(activity, "失败:" + code);
                        }
                    }

                    public void onError(int paramAnonymousInt, String paramAnonymousString) {
                        super.onError(paramAnonymousInt, paramAnonymousString);
                    }

                    public void onSuccess(List<ParentsCricleBean> paramAnonymousList) {
                        if (getDataType != 0) {
                            psView.onRefreshComplete();
                        }
                        if (paramAnonymousList != null) {
                            if (paramAnonymousList.size() < 10) {
                                isHasMore = false;
                            } else {
                                isHasMore = true;
                            }
                            if (getDataType != 2) {
                                parentsCricleBeans.clear();
                            }
                            if (HomeFragment.toBigImage == 0) {
                                parentsCricleBeans.addAll(paramAnonymousList);
                            }
                            pcAdapter = new ParentsCircleAdapter(getActivity(), parentsCricleBeans, new MyCallBack());
                            lvPc.setAdapter(pcAdapter);
                            pcAdapter.notifyDataSetChanged();
                        }

                        psView.onRefreshComplete();
                    }


                    @Override
                    public Type getType() {
                        return new TypeToken<List<ParentsCricleBean>>() {
                        }.getType();
                    }
                }

        );
    }

    public void initView(View paramView) {
        super.initView(paramView);
        context = new MainActivity();
        tvTitle = (TextView) paramView.findViewById(R.id.tv_common_title);
        tvTitle.setText("乖宝贝");
        ivMsg = (ImageView) paramView.findViewById(R.id.iv_common_msg);
        ivMsg.setVisibility(View.VISIBLE);
        rlMsg = (RelativeLayout) paramView.findViewById(R.id.rl_unread_msg);
        rlMsg.setVisibility(View.VISIBLE);
        rlMsg.setOnClickListener(this);
        tvUnreadMsg = (TextView) paramView.findViewById(R.id.tv_unread_num);
        ivUser = (ImageView) paramView.findViewById(R.id.iv_common_user);
        ivUser.setVisibility(View.VISIBLE);
        ivUser.setOnClickListener(this);
        psView = (PullToRefreshScrollView) paramView.findViewById(R.id.om_my_wallet_psv);
        lvPc = (MyListView) paramView.findViewById(R.id.lv_home);
        View localView = getActivity().getLayoutInflater().inflate(R.layout.home_header, null);
        tvAttendanceType = (TextView) localView.findViewById(R.id.tv_home_attendance_type);
        if (role == 2) {
            tvAttendanceType.setText("全园考勤小计");
        } else {
            tvAttendanceType.setText("本班考勤小计");
        }
        tvAttendanceDetail = (TextView) localView.findViewById(R.id.tv_home_attendance_detail);
        tvHot = (TextView) localView.findViewById(R.id.tv_hot);
        tvDistance = (TextView) localView.findViewById(R.id.tv_distance);
        tvSleep = (TextView) localView.findViewById(R.id.tv_sleep);
        tvWalk = (TextView) localView.findViewById(R.id.tv_walk);
        lvPc.addHeaderView(localView);
        editButtonView = (EditButtonView) paramView.findViewById(R.id.editButtonView);
        editButtonView.setOnButtonClickListener(this);
        editText = editButtonView.getEditText();
        inputMethMgr = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        psView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ScrollView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {
                if (psView.isHeaderShown()) {
                    refrush();
                } else if (psView.isFooterShown()) {
                    loadMore();
                }
            }
        });
        initAttendance();
        initSportsInfo();
        initUnReadMsgNum();
    }

    private void initUnReadMsgNum() {
        ActionHelp.getMessageInfo(getActivity(), new ObjectCallback<MessageInfo>() {
            @Override
            public void onError(int code) {
                if (code == 301) {
                    Intent intent = new Intent(getActivity(), LoginActivity.class);
                    startActivity(intent);
                } else {
                    ToastUtil.showToast(activity, "失败:" + code);
                }
                Log.e("code", code + "");
            }

            @Override
            public void onSuccess(MessageInfo response) {
                if (response.getUnReadNum() == 0) {
                    tvUnreadMsg.setVisibility(View.GONE);
                } else {
                    tvUnreadMsg.setVisibility(View.VISIBLE);
                    if (response.getUnReadNum() > 99) {
                        tvUnreadMsg.setText("99+");
                    } else {
                        tvUnreadMsg.setText(response.getUnReadNum() + "");
                    }
                }
            }

            @Override
            public Type getType() {
                return new TypeToken<MessageInfo>() {
                }.getType();
            }
        });
    }


    public void onButtonClick() {
        String str = editButtonView.getContent();
        if (TextUtils.isEmpty(str)) {
            Toast.makeText(getActivity(), getString(R.string.please_input_content), Toast.LENGTH_SHORT).show();
            return;
        }
        submitComment(mId, str, 0);
        ReviewBean localReviewBean = new ReviewBean();
        if (role == 2) {
            localReviewBean.setChildrenName(nickname + "园长");
        } else {
            localReviewBean.setChildrenName(nickname + "老师");
        }
        localReviewBean.setText(str);
        parentsCricleBeans.get(mPosition).getReviewlist().add(localReviewBean);
        pcAdapter.notifyDataSetChanged();
        hideSoftInput(editText);
    }

    public void onDestroyView() {
        super.onDestroyView();
    }

    public void onResume() {
        super.onResume();
        if (toBigImage == 0) {
            parentsCricleBeans.clear();
            pageNum = 1;
            initData();
        }
        toBigImage = 0;
        initAttendance();
        initSportsInfo();
        initUnReadMsgNum();
    }

    public void setUserVisibleHint(boolean paramBoolean) {
        super.setUserVisibleHint(paramBoolean);
    }

    public void showBottom() {
        editButtonView.setVisibility(View.GONE);
        editText.clearFocus();
        editText.setText("");
        MainActivity.llTabMain.setVisibility(View.VISIBLE);
        MainActivity.leftCenterButton.setVisibility(View.VISIBLE);
    }

    public void viewClick(View paramView) {
        super.viewClick(paramView);
        switch (paramView.getId()) {
            default:
                return;
            case R.id.iv_common_user:
                startActivity(new Intent(getActivity(), UserActivity.class));
                return;
            case R.id.rl_unread_msg:
                startActivity(new Intent(getActivity(), MessageActivity.class));
                return;
//            case R.id.btn_card:
//                if (!StringUtil.isEmpty(card.getTwoCreateOn_Time())) {
//                    ToastUtil.showToast(getActivity(), "今天已经完成打卡,请勿重复打卡！");
//                    return;
//                }
//                card();
//                break;
        }

    }

    public class MyCallBack
            implements ParentsCircleAdapter.ICallBack {
        public MyCallBack() {
        }

        public void AddComment(int position, int id) {
            mPosition = position;
            mId = id;
            showInputSoft(position);
        }

        public void deleMsg(int position, final int id) {
            mPosition = position;
            mId = id;
            delDialog = new CommonDialog(getActivity()) {
                protected void clickCancel(View paramAnonymousView) {
                    super.clickCancel(paramAnonymousView);
                    dismiss();
                }

                protected void clickOk(View paramAnonymousView) {
                    super.clickOk(paramAnonymousView);
                    delParentCircleMsg(id);
                }
            };
            delDialog.show();
        }

        public void praise(int position, int id) {
            mPosition = position;
            mId = id;

            int isPraise = 0;
            int praisePosition = 0;
            for (PraiseBean bean : parentsCricleBeans.get(mPosition).getPraiselist()) {
                if (bean.getIS_PRAISE() == 1) {
                    isPraise++;
                    break;
                }
                praisePosition++;
            }
            if (isPraise == 0) {
                submitComment(mId, "", 1);
                PraiseBean bean = new PraiseBean();
                if (role == 2) {
                    bean.setChildrenName(nickname + "园长");
                } else {
                    bean.setChildrenName(nickname + "老师");
                }
                bean.setIS_PRAISE(1);
                parentsCricleBeans.get(mPosition).getPraiselist().add(bean);
                pcAdapter.notifyDataSetChanged();
            } else {
                submitComment(mId, "", 2);
                parentsCricleBeans.get(mPosition).getPraiselist().remove(praisePosition);
                pcAdapter.notifyDataSetChanged();
            }

        }

        public void redirect(int position, int id) {
        }

        @Override
        public void gag(int position, int id, int userId, String type) {
            mPosition = position;
            mId = id;
            mUserId = userId;
            if (type.equals("Y")) {
                TimeDialog(tvTitle);
            } else {
                gagDialog = new CommonDialog(getActivity(), "确定取消禁言？") {
                    @Override
                    protected void clickCancel(View v) {
                        super.clickCancel(v);
                        dismiss();
                    }

                    @Override
                    protected void clickOk(View v) {
                        super.clickOk(v);
                        ActionHelp.gbbShieidMsg(getActivity(), "N", mUserId, new ObjectCallback<String>() {
                            @Override
                            public void onSuccess(String response) {
                                ToastUtil.showToast(getActivity(), "解除成功");
//                                initData();
                            }

                            @Override
                            public void onError(int code) {
                                if (code == 301) {
                                    Intent intent = new Intent(getActivity(), LoginActivity.class);
                                    startActivity(intent);
                                } else {
                                    ToastUtil.showToast(getActivity(), "解除失败");
                                }
                            }

                            @Override
                            public Type getType() {
                                return new TypeToken<String>() {
                                }.getType();
                            }
                        });
                    }
                };
                gagDialog.show();
            }
        }
    }

    public void TimeDialog(View paramView) {
        LayoutInflater mLayoutInflater = (LayoutInflater) getActivity()
                .getSystemService(getActivity().LAYOUT_INFLATER_SERVICE);
        //right_pop為泡泡的布局
        //View view = mLayoutInflater.inflate(R.layout.datetime_popupwindows, null);
        View view = mLayoutInflater.inflate(R.layout.popupwindows_gagtime, null);
        WLQQGagTimePicker localWLQQSexPicker = (WLQQGagTimePicker) view.findViewById(R.id.gag_time_picker);
        localWLQQSexPicker.setDate(1);
        localWLQQSexPicker.init(new TimeCallBack());
        popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setFocusable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        popupWindow.setOutsideTouchable(true);
        popupWindow.showAsDropDown(paramView);
    }

    public class TimeCallBack
            implements WLQQGagTimePicker.CallBack {
        @Override
        public void ConfirmAndGetData(int time) {
            popupWindow.dismiss();
            int timeout = 0;
            if (time == 0) {
                timeout = 60;
            } else if (time == 1) {
                timeout = 24 * 60;
            } else {
                timeout = 7 * 24 * 60;
            }
            ActionHelp.gbbShieidMsg(getActivity(), "Y", mId, mUserId, timeout, new ObjectCallback<String>() {
                @Override
                public void onSuccess(String response) {
                    ToastUtil.showToast(getActivity(), "禁言成功");
                    parentsCricleBeans.get(mPosition).setShieId("Y");
                    pcAdapter.notifyDataSetChanged();
//                    initData();
                }

                @Override
                public void onError(int code) {
                    if (code == 301) {
                        Intent intent = new Intent(getActivity(), LoginActivity.class);
                        startActivity(intent);
                    } else {
                        ToastUtil.showToast(getActivity(), "禁言失败");
                    }
                }

                @Override
                public Type getType() {
                    return new TypeToken<String>() {
                    }.getType();
                }
            });
        }

        @Override
        public void Cancel() {
            popupWindow.dismiss();
        }
    }

}
